package com.eliauk.demo.utils.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;

import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class DateConverter implements Converter<Date> {

    private static final String EXCEL_DATE_FORMAT = "yyyy.MM.dd";

    @Override
    public Class supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }


    //把 excel 的字符串类型转换成Date类型
    @Override
    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                  GlobalConfiguration globalConfiguration) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(EXCEL_DATE_FORMAT);
        String dateString = cellData.getStringValue();
        if (dateString != null) {
            return dateFormat.parse(dateString);
        }
        return null;
    }

    // 把java中的Date类型转换成 字符串类型写到excel中， 其实所有java类型都可以直接转成字符串再写到excel中
    @Override
    public WriteCellData<String> convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(EXCEL_DATE_FORMAT);
        return new WriteCellData<>(dateFormat.format(value));
    }
}
